from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse
from core.bilibili.manager import LiveRoomManager
import os
import sys
import importlib.util
CONFIG_API_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '../tools/config_api.py'))
spec = importlib.util.spec_from_file_location("config_api", CONFIG_API_PATH)
config_api = importlib.util.module_from_spec(spec)
sys.modules["config_api"] = config_api
spec.loader.exec_module(config_api)
import asyncio

router = APIRouter()

# 全局管理器单例（可根据实际项目结构优化）
room_manager = None

def get_room_manager():
    global room_manager
    if room_manager is None:
        config = config_api.get_config()
        room_manager = LiveRoomManager(config['bilibili']['room_id'])
    return room_manager

@router.post('/api/room/mute')
async def mute_user_api(req: Request):
    data = await req.json()
    uid = data.get('uid')
    minute = data.get('minute', 5)
    if not uid:
        return JSONResponse({'success': False, 'msg': '缺少uid'})
    try:
        manager = get_room_manager()
        ok = await manager.mute_user(int(uid), int(minute))
        return JSONResponse({'success': ok})
    except Exception as e:
        return JSONResponse({'success': False, 'msg': str(e)})

@router.post('/api/room/kick')
async def kick_user_api(req: Request):
    data = await req.json()
    uid = data.get('uid')
    if not uid:
        return JSONResponse({'success': False, 'msg': '缺少uid'})
    try:
        manager = get_room_manager()
        ok = await manager.kick_user(int(uid))
        return JSONResponse({'success': ok})
    except Exception as e:
        return JSONResponse({'success': False, 'msg': str(e)})
